package date.calendar;

import java.util.Calendar;

public class GetDayByWeek {
    static Integer[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    static int firstWeek = 0;//获取当前年份第一天是第一周的第几天
    static Integer m1 = 1;//周末所在月份
    static Integer m2 = 1;//周初所在月份

    static Integer year1 = -1;//周末所在年份
    static Integer year2 = -1;//周末所在年份

    public static void main(String[] args) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, 1);//设置一年的第一天

        firstWeek = calendar.get(Calendar.DAY_OF_WEEK);

        year1 = calendar.get(Calendar.YEAR);//按你的需求获取年份

        if ((year1 % 4 == 0 && year1 % 100 != 0) || year1 % 400 == 0)//判断是否为闰年
            month[1] = 29;
        else
            month[1] = 28;

        int days = getByWeek(1);//输入本年份第几周   返回该周的日期跨度
        getWeekMonth(days);

        int days2 = 0;
        if (days < 7)
            days2 = month[m2 - 1] + days - 6;
        else
            days2 = days - 6;

        System.out.println(year2 + "-" + m2 + "-" + (days2) + "到" + year1 + "-" + m1 + "-" + (days));


    }


    /**
     * @param week 一年的第几周
     * @return 该周最后一天是  m月days号
     */
    public static int getByWeek(int week) {

        int days = 0;//减去第一周跨两个月的天数
        if (firstWeek != 1) {//如果第一天不是周日 即一周的第一天
            days = week * 7 + 1 - firstWeek;
        } else {
            days = week * 7;
        }

        if (week > 1) {
            if (days < month[0] + firstWeek - 8) {
                m1 = 1;//第一个月
            } else {
                m1 = 1;
                for (int i = 0; days > month[i]; i++) {
                    days -= month[i];
                    m1++;
                }
            }
        }
        return days;
    }


    /**
     * 确定该周所跨月份 年份
     *
     * @param days 周末所在的日期（号数）
     */
    public static void getWeekMonth(int days) {

        if (days < 7) {
            if (m1 > 1) {
                m2 = m1 - 1;
                year2 = year1;
            } else {
                m2 = 12;
                year2 = year1 - 1;
            }
        } else {
            m2 = m1;
            year2 = year1;
        }
    }
}
